// 定义组合式API仓库
import { defineStore } from 'pinia'
import { getPrefixName } from '@/config'
import { constantRoutes } from "@/router";
const Layout = () => import('@/layout/index.vue')
const modules = import.meta.glob('../**/**.vue', { eager: false })

//创建小仓库
export default defineStore(getPrefixName('permission'), () => {
  const routers = ref([
    {
      path: '/',
      redirect: '/dashboard',
      component: 'Layout',
      children: [
        {
          path: '/dashboard',
          name: 'dashboard',
          meta: {
            title: '系统首页',
            icon: 'homepage'
          },
          component: 'views/HomeView'
        }
      ]
    },
    {
      path: '/system',
      component: 'Layout',
      meta: {
        title: '系统管理',
        icon: 'system'
      },
      children: [
        // {
        //   path: 'menu',
        //   name: 'Menu',
        //   meta: {
        //     title: '菜单管理',
        //     icon: 'menu'
        //   },
        //   component: 'views/system/menu/menuList'
        // },
        {
          path: 'user',
          name: 'User',
          meta: {
            title: '用户管理',
            icon: 'user'
          },
          component: 'views/system/user/UserList'
        },
        {
          path: 'dict',
          name: 'Dict',
          meta: {
            title: '字典管理',
            icon: 'dict'
          },
          component: 'views/system/dict/DictList'
        },
        {
          path: 'dict/item',
          name: 'DictItem',
          meta: {
            title: '字典项管理',
            icon: 'homepage',
            hidden: true
          },
          component: 'views/system/dictItem/DictItemList'
        }
      ]
    },
    {
      path: '/member',
      name: 'Member',
      component: 'Layout',
      children: [
        {
          path: 'list',
          name: 'MemberList',
          meta: {
            title: '会员列表',
            icon: 'peoples'
          },
          component: 'views/member/memberList'
        }
      ]
    },
    {
      path: '/goods',
      name: 'Goods',
      component: 'Layout',
      children: [
        {
          path: 'list',
          name: 'GoodsList',
          meta: {
            title: '商品列表',
            icon: 'goods'
          },
          component: 'views/goods/goodsList'
        }
      ]
    },
    {
      path: '/orders',
      name: 'Orders',
      component: 'Layout',
      children: [
        {
          path: 'list',
          name: 'OrdersList',
          meta: {
            title: '订单列表',
            icon: 'shopping'
          },
          component: 'views/orders/ordersList'
        }
      ]
    }
  ])

  // 动态路由是否添加
  const routesAdded = ref(false)

  /**
   * 设置动态路由添加成功
   */
  function setRoutesAdded(val: boolean) {
    routesAdded.value = val
  }

  /**
   * 递归过滤有权限的异步(动态)路由
   *
   * @param routes 接口返回的异步(动态)路由
   * @param roles 用户角色集合
   * @returns 返回用户有权限的异步(动态)路由
   */
  const filterAsyncRoutes = (routes: any[], roles: string[]) => {
    const asyncRoutes: any[] = []

    routes.forEach((route) => {
      const tmpRoute = { ...route } // ES6扩展运算符复制新对象

      // 判断用户(角色)是否有该路由的访问权限
      // if (hasPermission(roles, tmpRoute)) {
      if (tmpRoute.component?.toString() == 'Layout') {
        tmpRoute.component = Layout
      } else {
        console.log(tmpRoute.component, )
        const component = modules[`../${tmpRoute.component}.vue`]
        console.log(component, 'component')
        if (component) {
          tmpRoute.component = component
        } else {
          tmpRoute.component = modules[`../../views/error-page/404.vue`]
        }
      }

      if (tmpRoute.children) {
        tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles)
      }

      asyncRoutes.push(tmpRoute)
      // }
    })

    return asyncRoutes
  }

  function setRoutes(newRoutes: any[]) {
    // routers.value = constantRoutes.concat(newRoutes);
}

  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: string[]) {
    return new Promise<any[]>((resolve, reject) => {
      // 接口获取所有路由
    //   listRoutes()
        // .then(({ data: asyncRoutes }) => {
          // 根据角色获取有访问权限的路由
          const accessedRoutes = filterAsyncRoutes(routers.value, roles)
          setRoutes(accessedRoutes)
          resolve(accessedRoutes)
        // })
        // .catch((error) => {
        //   reject(error)
        // })
    })
  }

  return {
    routesAdded,
    routers,
    setRoutesAdded,
    generateRoutes
  }
}, {
  persist: false
})
